package com.groep14.project;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.groep14.model.Person;

/**
 * De LoginController handelt requests met de loginpagina af.
 * 
 * @since r28 - 31 Maart 2012
 * @author Maarten Tutak
 *
 */

@Controller
public class LoginController {

	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	private MyLogger myLogger = new MyLogger();
	private  StandardPasswordEncoder encoder;
	
	/**
	 * De doLogin methode word gebruikt om klanten in te loggen dmv hun E-mailadres en wachtwoord.
	 * 
	 * @param request
	 * @param session
	 * @param response
	 * @return ModalAndView
	 */
	
	@RequestMapping(value = "/dologin",method = RequestMethod.POST)
	public ModelAndView doLogin(HttpServletRequest request,HttpSession session,HttpServletResponse response) {
		
		logger.info("Login process started");
		Boolean blnAdmin = false;
		
		try {
			
			Validator validator = new Validator();
			
			if (validator.validateEmail(request.getParameter("username")) &&
				validator.validateString(request.getParameter("password"), 0, 50, true, true, true)){
				
				Connectie con = new Connectie();
				ResultSet result = null;
				
				con.setpStatement(con.getCon().prepareStatement("SELECT * FROM Persons WHERE Mbox = ?"));
				con.getpStatement().setString(1, request.getParameter("username"));
										
				result =  con.getpStatement().executeQuery();
				
				if(result.next()) {
					
					//Password encryptie.
					encoder = new StandardPasswordEncoder(request.getParameter("username"));
					
					if(encoder.matches(request.getParameter("password"), result.getString("Password"))) {
						logger.info("The password matches the password in the database ! ");
					} else {
						logger.info("The password is wrong !");
						return new ModelAndView("login","error","Login mislukt, je password is verkeerd !");
					}		
					
					logger.info("Login succes :)");
					
					Person person = new Person();
					person.setPers_id(result.getInt("Pers_id"));
					person.setLastname(result.getString("Lastname"));
					person.setFirstname(result.getString("Firstname"));
					person.setBirthday(result.getDate("Birthday"));
					person.setGender(result.getString("Gender"));
					person.setPhone(result.getString("Phone"));
					person.setCellphone(result.getString("Cellphone"));
					person.setMbox(result.getString("Mbox"));
					person.setCountry(result.getString("Country"));
					person.setStreetAdress(result.getString("StreetAdress"));
					person.setZip(result.getString("Zip"));
					person.setAdmin(result.getInt("Admin"));
					
					if (person.getAdmin() == 1) {
						blnAdmin = true;
					}
					
					logger.info("Saving Person in session..");
					session.setAttribute("person", person);
					
				}else {
					logger.info("Login failed :(");
					return new ModelAndView("login","error","Login mislukt, je hebt nog geen account !");
				}
				
			} else {
				logger.info("Not valid");
			}

		} catch (SQLException e) {
			myLogger.logException(getClass() + " - ", e);
		} catch (ClassNotFoundException e) {
			myLogger.logException(getClass() + " - ", e);
		} catch (InstantiationException e) {
			myLogger.logException(getClass() + " - ", e);
		} catch (IllegalAccessException e) {
			myLogger.logException(getClass() + " - ", e);
		}
		
		if (blnAdmin) {
			return new ModelAndView("redirect:admin");
		}
		
		return new ModelAndView("redirect:index");
	}

	/**
	 * De logout methode word gebruikt om klanten uit te loggen, de bestaande sessies worden vernietigd.
	 * 
	 * @param session
	 * @return modelAndView
	 */
	
	@RequestMapping(value="logout",method=RequestMethod.GET)
	public ModelAndView logout(HttpSession session) {
		
		session.removeAttribute("person");
		session.removeAttribute("ShoppingCart");
		session.removeAttribute("ShoppingCartList");
		return new ModelAndView("redirect:index");
	}
}
